package web.weibo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import web.weibo.mapper.MapperWeibo;

@Service
public class ServiceExample {
    // http://mybatis.org/spring/transactions.html
    private final PlatformTransactionManager transactionManager;
    @Autowired
    MapperWeibo mapperWeibo;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public ServiceExample(
            PlatformTransactionManager transactionManager
    ) {
        this.transactionManager = transactionManager;
    }

    public String TtransactionExample() {
        TransactionStatus txStatus =
                transactionManager.getTransaction(new DefaultTransactionDefinition());
        try {
            mapperWeibo.weiboAdd("测试事务插入", "2021", 1);
            // throw new RuntimeException("测试回滚");
        } catch (Exception e) {
            transactionManager.rollback(txStatus);
            throw e;
        }
        transactionManager.commit(txStatus);
        return "事务执行成功！";
    }

    public String redisExample() {
        stringRedisTemplate.opsForValue().set("web26", "lxq");
        String value = stringRedisTemplate.opsForValue().get("web26");
        return value;
    }

    // redis緩存，存取临时数据
    public String cacheExample() {
        String key = "countWeibo";
        String countString = stringRedisTemplate.opsForValue().get(key);
        if (countString == null) {
            int count = mapperWeibo.countWeibo();
            String result = String.valueOf(count);
            stringRedisTemplate.opsForValue().set(key, result);
            return result;
        } else {
            String result = countString;
            return result;
        }
    }
}
